//
//  CMCircularMap.m
//  饼状图
//
//  Created by tanqilong on 16/8/24.
//  Copyright © 2016年 tanqilong. All rights reserved.
//

#import "CMPieChartMap.h"

@interface CMPieChartMap ()
{
    BOOL _isLayoutSubViews;
}
@property (nonatomic,strong) UIImageView * imageView;
@end

@implementation CMPieChartMap

-(void)awakeFromNib {
    [self commonInit];
}

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

-(void)commonInit {
    self.imageView = [[UIImageView alloc]initWithFrame:self.bounds];
    [self addSubview:_imageView];
    self.lineWidthPercent = 3.0 / 5.0;
}

-(void)layoutSubviews {
    [super layoutSubviews];
    if (!_isLayoutSubViews) {
        self.lineWidth = self.bounds.size.width / 2.0 * self.lineWidthPercent;
        [self updateView];
    } else {
        _isLayoutSubViews = YES;
    }
}

-(void)updateView {
    float startPercent = 0;
    float endPercent = 0;
    CALayer * containerLayer = [CALayer layer];
    containerLayer.frame = self.bounds;
    //拼接layer
    for (CMPieChartMode * mode in self.modeArray) {
        startPercent = endPercent;
        endPercent += mode.percent;
        CAShapeLayer * arcLayer = [self generateLayerWidth:self.lineWidth StartPercent:startPercent EndPercent:endPercent Color:mode.color];
        [containerLayer addSublayer:arcLayer];
    }
    //合并图层
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, containerLayer.contentsScale);
    CGContextRef ref = UIGraphicsGetCurrentContext();
    [containerLayer renderInContext:ref];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.imageView.image = image;
}

//生层一个弧形
-(CAShapeLayer *)generateLayerWidth:(CGFloat)witdh StartPercent:(CGFloat)startPercent EndPercent:(CGFloat)endPercent Color:(UIColor *)color {
    UIBezierPath * path = [UIBezierPath new];
    [path addArcWithCenter:CGPointMake(self.bounds.size.width/2.0, self.bounds.size.width/2.0) radius:self.bounds.size.width/2.0 - witdh/2.0 startAngle:-M_PI_2 endAngle:3 * M_PI_2 clockwise:YES];
    CAShapeLayer * shapLayer = [CAShapeLayer layer];
    shapLayer.strokeColor = [color CGColor];
    shapLayer.fillColor = nil;
    shapLayer.lineWidth = witdh;
    shapLayer.strokeStart = startPercent; //起始百分比
    shapLayer.strokeEnd = endPercent; //结束百分比
    shapLayer.path = path.CGPath;
    return shapLayer;
}

@end


@implementation CMPieChartMode


@end
